<template>
  <el-card>
    <el-form class="outer1">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请输入职位关键字"
          style="width: 200px"
          v-model="keyWord"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="default"
          style="
            background-color: rgb(83, 114, 237);
            color: aliceblue;
            width: 50px;
          "
          :disabled="keyWord ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button
          size="default"
          style="
            background-color: rgb(83, 114, 237);
            color: aliceblue;
            width: 50px;
          "
          @click="reset"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button
      type="primary"
      size="default"
      icon="Plus"
      style="
        background-color: rgb(83, 114, 237);
        color: aliceblue;
        width: 100px;
      "
      @click="addRole"
    >
      添加角色
    </el-button>
    <el-table border style="margin: 10px 0" :allRole="allRole">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column align="center" label="ID" prop="id"></el-table-column>
      <el-table-column
        align="center"
        label="职位名称"
        show-overflow-tooltip
        prop="roleName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column align="center" label="操作" width="260px">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="default"
            icon="User"
            @click="setPermission(row)"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="default"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.roleName}?`"
            @confirm="removeRole(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="default" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器 -->
    <el-pagination
      @size-change="sizeChange"
      @current-change="getHasRole"
      v-model:current-page="pageNo"
      :page-sizes="[3, 5, 7, 9]"
      v-model:page-size="pageSize"
      layout=" prev, pager, next, jumper,->,sizes,total "
      :total="total"
    ></el-pagination>

    <!-- 测试按钮 -->
    <el-button size="default" icon="User" @click="setPermission1">
      分配权限
    </el-button>
    <el-button size="default" icon="Edit" @click="updateRole1">编辑</el-button>
    <el-popconfirm :title="`你确定要删除该角色吗?`" @confirm="removeRole">
      <template #reference>
        <el-button size="default" icon="Delete">删除</el-button>
      </template>
    </el-popconfirm>
  </el-card>
  <!-- 新增和编辑时显示对话框 -->
  <el-dialog
    v-model="dialogVisite"
    :title="RoleParams.id ? '修改职位' : '添加职位'"
  >
    <el-form :model="RoleParams" :rules="rules" ref="formRef">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          v-model="RoleParams.roleName"
          placeholder="请输入职位名称"
          style="width: 300px"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        style="
          background-color: rgb(83, 114, 237);
          color: aliceblue;
          width: 50px;
        "
        size="default"
        @click="dialogVisite = false"
      >
        取消
      </el-button>
      <el-button
        style="
          background-color: rgb(83, 114, 237);
          color: aliceblue;
          width: 50px;
        "
        size="default"
        @click="save"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件:分配职位按钮时显示 -->
  <el-drawer v-model="drawer">
    <template #header><h1>分配职位</h1></template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        :data="data"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="[1, 3]"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <el-button
        type="primary"
        size="default"
        style="
          background-color: rgb(83, 114, 237);
          color: aliceblue;
          width: 100px;
        "
        @click="handler"
      >
        确定
      </el-button>
      <el-button
        type="primary"
        size="default"
        @click="drawer = false"
        style="
          background-color: rgb(83, 114, 237);
          color: aliceblue;
          width: 100px;
        "
      >
        取消
      </el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRoleList,
  reqRemoveRole,
  reqSetPermission,
} from '@/api/acl/role'
import type {
  MenuData,
  MenuList,
  MenuResponseData,
  Records,
  RoleData,
  RoleResponseData,
} from '@/api/acl/role/type'
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入控制刷新的仓库并使用仓库
import useHomeSettingStore from '@/store/setting'
import { ElMessage } from 'element-plus'
// import tree from 'element-plus/es/components/tree/index.mjs'
let settingStore = useHomeSettingStore()
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(100)
//收集职位搜索的关键字
let keyWord = ref<string>('')
//存储已有的全部职位以及角色相关信息
let allRole = ref<Records>([])
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false)
//收集新增和修改的职位的的参数,可用来展示已有数据(row)和清空表单信息
let RoleParams = reactive<RoleData>({
  roleName: '',
})
//校验表单的组件实例,点击确定按钮发送请求之前通过表单实例对整个表单校验通过再发请求
let formRef = ref()
//控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
//定义数组存储用户权限的数据
let menuArr = ref<MenuList>([])
//定义一个数组用来存储已有权限的id(四级id),已选中的权限
let selectArr = ref<any>([])
//拿到树形控件的实例
let tree = ref()
onMounted(() => {
  //挂载获取角色信息
})
//获取角色的方法
async function getHasRole(pager = 1) {
  pageNo.value = pager
  let result: any = (await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyWord.value,
  )) as unknown as RoleResponseData
  allRole = result.data
  total = result.data.total
}
//分页器下拉菜单的回调
function sizeChange() {
  //默认回到第一页
  getHasRole()
}
//搜索按钮的回调
function search() {
  //根据关键字发请求
  getHasRole()
  keyWord.value = ''
}
//重置按钮的回调
function reset() {
  settingStore.Refresh = !settingStore.Refresh
}
//添加职位按钮的回调
function addRole() {
  dialogVisite.value = true
  //清空数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  })
  //清空某个字段校验的结果
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
//更新职位按钮的回调
function updateRole(row: RoleData) {
  dialogVisite.value = true
  //存储已有的职位
  Object.assign(RoleParams, row)
}
function updateRole1(id = 1) {
  dialogVisite.value = true
  RoleParams.id = id
}

//新增职位名称校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
//自定义校验规则
function validatorRoleName(_rules: any, value: any, callBack: any) {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
//添加或修改对话框确定按钮的回调
async function save() {
  await formRef.value.validate()
  dialogVisite.value = false
  //发送添加或者更新职位的请求
  let result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '修改成功' : '添加成功',
    })
    dialogVisite.value = false
    //获取更新后的信息
    getHasRole(RoleParams.id ? pageNo.value : 1)
  }
}
//分配权限按钮的回调
//row代表已有职位的数据,需要获取职位的id
async function setPermission(row: RoleData) {
  drawer.value = true
  //收集当前职位id
  Object.assign(RoleParams, row)
  //根据职位id获取相应的权限数据
  let result: any = (await reqAllMenuList(
    RoleParams.id as number,
  )) as unknown as MenuResponseData
  if (result.code === 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
function setPermission1() {
  drawer.value = true
}
//过滤职位已有的权限用来勾选显示
function filterSelectArr(allData: any, initArr: any) {
  allData.forEach((item: any) => {
    //判断四级分类的是否勾选
    if (item.select && item.leval == 4) {
      initArr.push(item.id)
    }
    //递归逐级判断item.select是否为真，直到leval=4
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
}
//分配权限确定按钮发送请求
async function handler() {
  //收集数据
  const roleId = RoleParams.id as number
  //选中节点的id,返回目前选中的节点所组成的数组,getCheckedKeys方法需要通过树形控件实例来使用
  let arr = tree.value.getCheckedKeys()
  //半选id,	若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点所组成的数组
  let arr1 = tree.value.getHalfCheckedKeys()
  //权限id包括选中和半选的id
  let permissionId = arr.concat(arr1)
  //下发权限发送请求
  let result: any = await reqSetPermission(roleId, permissionId)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
  }
}
//删除角色回调
async function removeRole(id: number) {
  let result: any = await reqRemoveRole(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasRole(allRole.value.length >= 1 ? pageNo.value : pageNo.value - 1)
  }
}

//树形控件数据
//响应数据的展示字段
const defaultProps = {
  children: 'children',
  label: 'label',
}
const data = [
  {
    id: 1,
    label: '一级 1',
    children: [
      {
        label: '二级 1-1',
        children: [
          {
            label: '三级 1-1-1',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: '一级 2',
    children: [
      {
        label: '二级 2-1',
        children: [
          {
            label: '三级 2-1-1',
          },
        ],
      },
      {
        label: '二级 2-2',
        children: [
          {
            label: '三级 2-2-1',
          },
        ],
      },
    ],
  },
  {
    id: 3,
    label: '一级 3',
    children: [
      {
        label: '二级 3-1',
        children: [
          {
            label: '三级 3-1-1',
          },
        ],
      },
      {
        label: '二级 3-2',
        children: [
          {
            label: '三级 3-2-1',
          },
        ],
      },
    ],
  },
]
</script>

<style scoped lang="scss">
.outer1 {
  display: flex;
  justify-content: space-between;
}
</style>
